package uniandes.moviles.antid.interfaz;

import uniandes.moviles.antid.R;
import uniandes.moviles.antid.mundo.PersistenceManager;
import uniandes.moviles.antid.mundo.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	
	/**
	 * Identifies the login error dialog
	 */
	public static final int DIALOG_ERROR = 1;
	
	/**
	 * Represents the login button of the activity.
	 */
	private Button btnLogin;
	
	/**
	 * Represents the register button of the activity.
	 */
	private Button btnRegister;
	
	/**
	 * Manages the persistence of the application.
	 */
	private PersistenceManager manager;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        manager = new PersistenceManager(this);
        inicializarBotones();
    }
    
    private void inicializarBotones()
    {
    	btnLogin = (Button)findViewById(R.id.btnLogin);
    	btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int role = login();
				if(role == 1)
				{
					
				}
				else if(role == 0)
				{
					
				}
			}
		});
    	btnRegister = (Button)findViewById(R.id.btnRegister);
    	btnRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
    }
    
    /**
     * Tries to log the user to the application by checking the activity text fields's text in the data base.
     */
    private int login()
    {
    	int role = -1;
    	User user = new User(manager){} ;
		EditText txtUName = (EditText) findViewById(R.id.txtUName);
		EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
		String userName = txtUName.getText().toString();
		String password = txtPassword.getText().toString();
		try
		{
			role = user.login(userName, password);			
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			showDialog(DIALOG_ERROR);
		}
		return role;
    	
    }
    
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateDialog(int)
     */
    protected Dialog onCreateDialog(int id) {
    	switch(id)
		{
			case DIALOG_ERROR:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("User name or password are incorrect.");
				builder.setCancelable(false);
				builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();				                
				           }
				 });
				AlertDialog alert = builder.create();
				return alert;
		}
    	return null;
    	
    }
    
}